<template>
  <div>
    <el-select
      v-model="ids"
      :multiple="multiple"
      style="width: 100%"
      @change="handleChange"
      :placeholder="$t('labels.pleaseSelect')"
    >
      <el-option
        v-for="item in roles"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select>
  </div>
</template>
<script>
import { getAllRoles } from "@/api/role";
export default {
  data() {
    return {
      roles: [],
      ids: [],
      values: [],
    };
  },
  model: {
    prop: "roleNames",
    event: "change",
  },
  methods: {
    getData() {
      getAllRoles().then((res) => {
        this.roles = res ? res.items : [];
      });
    },
    handleChange() {
      this.values = [];
      let selectedRoles = this.getSelectedRoles();
      this.values = selectedRoles.map((role) => {
        return role.name;
      });
      this.$emit("change", this.values);
    },
    getSelectedRoles() {
      if (!this.roles || this.roles.length == 0) return [];
      if (!this.ids || this.ids.length == 0) return [];
      let result = this.roles.filter((role) => {
        return this.ids.includes(role.id);
      });

      return result;
    },
    setRoleIds() {
      if (
        !this.roles ||
        this.roles.length == 0 ||
        !this.roleNames ||
        this.roleNames.length == 0
      )
        this.ids = [];
      else {
        let matchRoles = this.roles.filter((role) => {
          return this.roleNames.includes(role.name);
        });
        this.ids = matchRoles
          ? matchRoles.map((role) => {
              return role.name;
            })
          : [];
      }
    },
  },
  watch: {
    roleIds: {
      handler(value) {
        if (value && value.length > 0) {
          this.ids = value;
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.getData();
    });
  },
  props: {
    multiple: {
      type: Boolean,
      default: false,
    },
    roleNames: {
      type: Array,
      default: () => [],
    },
    roleIds: {
      type: Array,
      default: () => [],
    },
  },
};
</script>
